package com.zzp;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTx {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "zzp");

        String json = jsonObject.toJSONString();

        Transaction multi = jedis.multi();  // 开启事务

        try {
            multi.set("user1", json);
            multi.set("user2", json);

//            int i= 1 / 0; //手动加一个异常

            multi.exec(); // 执行事务
        }catch (Exception e){
            multi.discard();  // 放弃事务
            e.printStackTrace();

        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));

            jedis.close();  //关闭连接
        }

    }
}
